#!/usr/bin/env python
#coding=utf-8

import os
import ConfigParser
import sys
import getopt
import threading
from common import unit
from common.log import logger


"""
通过ssh执行多任务管理器  入口
"""


def usage():
    """
    使用说明
    """
    print "Usage:"
    print "    python easytasks.py -d -f config.ini -n pgname -c command -h host:port -u username -p passwd -k key [--help]"
    print "\t-d\t\t使用默认配置的ini文件"
    print "\t-f\t\t自定义配置的ini文件"
    print "\t-n\t\t项目名称"
    print "\t-c\t\t执行命令"
    print "\t-h\t\t主机IP:端口"
    print "\t-u\t\t用户名"
    print "\t-p\t\t密码"
    print "\t-k\t\t密钥文件"

    

if __name__ == '__main__':

    #获取当前脚本执行的目录
    root_dir = os.path.abspath(os.path.dirname(__file__))
    
    #将当前目录加入到python环境变量
    sys.path.append(root_dir)
    
    #判断参数至少有一个
    if len(sys.argv) <=1:
        print "\033[31;1m[Error]===>请指定参数\033[0m"
        usage()
        sys.exit(0)
        

    #输入参数错误引起的异常
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'df:n:h:u:p:k:c:',["help"])
    except getopt.GetoptError,e:
        print "\033[31;1m[Error]===>",e,"\033[0m"
        usage()
        sys.exit(0)
    
    cfile = None
    pgname = None
    cmd = None
    host = None
    username = None
    passwd = None
    key = None
    defaultconfig = False
    #定义是否使用配置文件
    usefile = False
    
    for op, value in opts:
        if op == '-d':
            defaultconfig = True
            usefile = True
        elif op == '-f':
            cfile = value
            usefile = True
        elif op == '-h':
            host = value
        elif op == '-n':
            pgname = value
        elif op == '-u':
            username = value
        elif op == '-p':
            passwd = value
        elif op == '-k':
            key = value
        elif op == '-c':
            cmd = value
        elif op == '--help':
            usage()
            sys.exit(0)

    if usefile:

        if defaultconfig:
            #使用默认配置的ini文件
    
            #配置文件路径
            config_file = os.path.join(root_dir,'config','config.ini')
        else:
            if cfile is None:
                print "\033[31;1m[Error]===> 指定配置文件或者使用-d参数,使用默认配置文件\033[0m"
                sys.exit(0)
                
            config_file = cfile
            
    
        if not os.path.isfile(config_file):
            #文件不存在
            print "\033[31;1m[Error]===> 文件不存在\033[0m"
            sys.exit(0)
        
        try:
            taskdata = unit.readconfig(config_file,pgname=pgname)
            
            for i in taskdata:
                if i.has_key('passwd'):
                    a = threading.Thread(target=unit.ssh_passwd,args=(i['ip'],i['port'],i['username'],i['passwd'],i['cmd']))
                else:
                    a = threading.Thread(target=unit.ssh_key,args=(i['ip'],i['port'],i['username'],i['key'],i['cmd']))
            
                a.start()
                
        except ConfigParser.NoSectionError,e:
            #没有对应的项目
            print "\033[31;1m[Error]===> ",e,"\033[0m"
            sys.exit(0)        
        except ConfigParser.MissingSectionHeaderError,e:
            #配置文件格式错误
            print "\033[31;1m[Error]===> ",e,"\033[0m"
            sys.exit(0)                


    else:
        
        if host is None or cmd is None or username is None:
            print "\033[31;1m[Error]===> 用户名、主机、执行命令不能为空 \033[0m"
            sys.exit(0)
            
        if ":" in host:
            ip = host.split(':')[0]
            port = int(host.split(':')[1])
        else:
            ip = host
            port = 22
        
        if passwd is not None:
            unit.ssh_passwd(ip,port,username,passwd,cmd)
        elif key is not None:
            unit.ssh_key(ip,port,username,key,cmd)
        else:
            passwd = None
            unit.ssh_passwd(ip,port,username,passwd,cmd)
            